import { _decorator, BoxCollider2D, Camera, Component, Contact2DType, Director, director, ERigidBody2DType, find, instantiate, Node, Prefab, resources, RigidBody, RigidBody2D, Skeleton, sp, tween, UITransform, v2, v3 } from 'cc';
import { biontTypeEnum } from './Enum';
import { Dictionary } from './Dictionary';
import { Biont } from './Biont';
import { getDistance, isNearlyEqual, randowNum, trackTarget } from './utils';
import { gameMgr } from './GameMgr';
import { Prop } from './Prop';
import { TouchMove } from './TouchMove';
import { UserInfo } from './UserInfo';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('Player')
export class Player extends Component {

    @property([sp.SkeletonData])
    biontsSpineDataArr: sp.SkeletonData[] = []
    @property([Prefab])
    additionBionPreArr: Prefab[]=[];

    static ins: Player = null;
    protected onLoad(): void {
        Player.ins = this;
    }

    private isImmortal = false;
    set IsImmortal(value) {
        if (this.isImmortal == value) {
            return;
        }
        this.isImmortal = value

        if (value == true) {
            if (this.node.children[0]) {
                this.node.children[0].getChildByName("shield2").active = true
                console.log("shield2", this.node.children[0].getChildByName("shield2").active = true)

            }
            if (!UserInfo.isWudiMode) {
                this.scheduleOnce(() => { this.IsImmortal = false }, 7)
            }
        }
        else {
            if (this.node.children[0]) {
                this.node.children[0].getChildByName("shield2").active = false
            }
        }
    }
    get IsImmortal() {
        return this.isImmortal;
    }
    private isSpeedUp = false;
    set IsSpeedUp(value) {
        if (this.isSpeedUp == value) {
            return;
        }
        if (value == true) {
            TouchMove.ins.moveSpeed = 15
            this.scheduleOnce(() => { this.IsSpeedUp = false }, 7)
        }
        else {
            TouchMove.ins.moveSpeed = 10

        }
        this.isSpeedUp = value
    }
    get IsSpeedUp() {
        return this.isSpeedUp;
    }

    biontId = 0;

    currControlBiontType = 0;

    hasBiontsDic: Dictionary<number, number> = new Dictionary();//玩家拥有的生物字典，包含自己


    protected start(): void {
        // this.node.children[0].getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT, this.beginContact)
        // this.node.getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT,this.beginContact)
        this.hasBiontsDic.set(999, this.currControlBiontType);
        console.log("初始字典",this.hasBiontsDic)
        this.IsImmortal = true
        // this.node.removeFromParent()
    }

    beginContact(selfC, otherC, contact) {
        console.log("触发")
        director.once(Director.EVENT_AFTER_PHYSICS, () => {
            if (otherC.tag == 77) {
                console.log("碰到道具了")
                switch (otherC.getComponent(Prop).propType) {
                    case 0:
                        Player.ins.IsSpeedUp = true;
                        break;
                    case 1:
                        Player.ins.IsImmortal = true;
                        break;
                }
                otherC.node.destroy();
                return
            }
            if (otherC.tag > Player.ins.currControlBiontType) {
                if (Player.ins.IsImmortal == true) {
                    console.log("无敌不死")
                }
                else {
                    Player.ins.die();
                    console.log("游戏结束")
                }
            }
            else {
                console.log(99)
                Player.ins.captureBiont(otherC.tag);
                if (otherC.node.getComponent(Biont)) {
                    gameMgr.ins.existBiontsDic.delete(otherC.node.getComponent(Biont).biontId)

                }
                otherC.node.destroy()
            }

        })

    }

    //捕捉到生物
    captureBiont(biontType) {
        AudioMgr.ins.playOneShot("audio/countDown", 0.7)
        gameMgr.ins.currExistBiontsTotalNum -= 1
        console.log("捕捉")
        this.generateBiont(biontType);

        // setTimeout(() => {
            console.log(this.hasBiontsDic, "捕捉到的生物子字典")

            while (this.judgeIsHasThereBiont().length > 0) {
                console.log("合成自己0.1")
                let resArr = this.judgeIsHasThereBiont();
                if (resArr && resArr.length > 0) {//可以合成
                    if (this.currControlBiontType <= resArr[0]) {
                        console.log("合成自己")
                        this.selftChangeBiont(resArr[0] + 1)
    
                        this.hasBiontsDic.deleteValue(resArr[0]);
                        this.hasBiontsDic.deleteValue(resArr[1]);
                        // if (resArr.length>=3) {
                        this.hasBiontsDic.deleteValue(resArr[2]);
                        // }
                        this.hasBiontsDic.delete(999)
                        this.hasBiontsDic.set(999, resArr[0] + 1);
    
                        this.reGenerateBiont();
                    }
                    else {
                        console.log("合成附属")
    
                        this.hasBiontsDic.deleteValue(resArr[0]);
                        this.hasBiontsDic.deleteValue(resArr[1]);
                        if (resArr.length == 3) {
                            this.hasBiontsDic.deleteValue(resArr[2]);
                        }
    
                        this.hasBiontsDic.set(this.biontId, resArr[0] + 1);
                        this.biontId += 1
                        this.reGenerateBiont();
    
                    }
    
    
                }
                else {
                    console.log("不能合成")
                    break;
    
                }
    
            }
        // }, 50);
    


    }

    generateBiont(biontType) {
        this.hasBiontsDic.set(this.biontId, biontType)
            this.biontId += 1
        // resources.load(`prefabe/additionPre/${biontType}`, Prefab, (err, res) => {
            // let pre = instantiate(gameMgr.ins.additionBiontPrefabArr[biontType]);
            let pre = instantiate(this.additionBionPreArr[biontType]);
            pre.setParent(this.node.parent.getChildByName("otherBiontRoot"));
            pre.angle = 0;

            let randCount = randowNum(0, 1);
            let resY;
            if (randCount == 0) {
                resY = randowNum(-60, -100)
            }
            else {
                resY = randowNum(60, 100)
            }


            if (biontType ==  biontTypeEnum.shayu2) {
                pre.setPosition(v3(randowNum(-180, -280), resY, 0))
            }
            else if (biontType == biontTypeEnum.changlong||biontType == biontTypeEnum.shayu1) {
                pre.setPosition(v3(randowNum(-310, -410), resY, 0))
            }
            else {
                pre.setPosition(v3(randowNum(-180, -110), resY, 0))
            }

            if (biontType == biontTypeEnum.wugui || biontType == biontTypeEnum.changlong) {
                pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "walk", true)
            }
            else {
                pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "animation", true)
            }

            
        // })

    }

    reGenerateBiont() {
        console.log(this.hasBiontsDic.getValueList(), "this.hasBiontsDic.getValueList()")
        let otherBiontRoot = this.node.parent.getChildByName("otherBiontRoot");
        otherBiontRoot.removeAllChildren();

    this.hasBiontsDic.getKeyList().forEach((ele) => {
        if (ele == 999) {
            return;
        }
        // resources.load(`prefabe/additionPre/${this.hasBiontsDic.get(ele)}`, Prefab, (err, res) => {
        
            // let pre = instantiate(res);
            // let pre = instantiate(gameMgr.ins.additionBiontPrefabArr[this.hasBiontsDic.get(ele)]);
            let pre = instantiate(this.additionBionPreArr[this.hasBiontsDic.get(ele)]);

            pre.setParent(this.node.parent.getChildByName("otherBiontRoot"));

            let randCount = randowNum(0, 1);
            let resY;
            if (randCount == 0) {
                resY = randowNum(-60, -100)
            }
            else {
                resY = randowNum(60, 100)
            }

            if (this.hasBiontsDic.get(ele) ==  biontTypeEnum.shayu2) {
                pre.setPosition(v3(randowNum(-180, -280), resY, 0))
            }
            else if (this.hasBiontsDic.get(ele) == biontTypeEnum.changlong||this.hasBiontsDic.get(ele) == biontTypeEnum.shayu1) {
                pre.setPosition(v3(randowNum(-310, -410), resY, 0))
            }
            else {
                pre.setPosition(v3(randowNum(-180, -110), resY, 0))
            }

            if (this.hasBiontsDic.get(ele) == biontTypeEnum.wugui || this.hasBiontsDic.get(ele) == biontTypeEnum.changlong) {
                pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "walk", true)
            }
            else {
                pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "animation", true)
            }

            pre.angle = 0;
        // })
    })
       
    }

    //判断是否有三个一样的生物
    judgeIsHasThereBiont() {
        let typeArr = [this.currControlBiontType]
        let tempCount = 0;
        let resType = -1;
        let resArr = []
        this.hasBiontsDic.getValueList().forEach((ele) => {
            if (typeArr.indexOf(ele) == -1) {
                typeArr.push(ele)
            }
        })
        for (let t = 0; t < typeArr.length; t++) {
            tempCount = 0;
            for (let i = 0; i < this.hasBiontsDic.getValueList().length; i++) {
                console.log("执行到循环了")
                if (this.hasBiontsDic.getValueList()[i] == typeArr[t]) {
                    tempCount += 1

                    // if (tempCount == 2 && typeArr[t] == this.currControlBiontType) {
                    //     console.log("44")
                    //     resType = typeArr[t]
                    // }
                    if (tempCount == 3) {

                        resType = typeArr[t]
                    }
                }

            }

        }

        if (resType != -1) {
            this.hasBiontsDic.getValueList().forEach((ele) => {
                if (ele == resType) {
                    resArr.push(ele)
                }
            })
        }
        return resArr;
    }

    selftChangeBiont(biontType) {

        if (biontType == gameMgr.ins.totalBiontTypeNum) {//通关
            gameMgr.ins.gameEnd();
            return;
        }
        this.currControlBiontType = biontType;
        // this.node.children[0].getComponent(BoxCollider2D).off(Contact2DType.BEGIN_CONTACT,this.beginContact)
        this.node.removeAllChildren()
        this.hasBiontsDic.delete(999)
        this.hasBiontsDic.set(999, biontType)
        resources.load(`prefabe/playerPre/${biontType}`, Prefab, (err, res) => {
            let pre = instantiate(res);
            pre.setParent(this.node);
            pre.setPosition(0, 0, 0)
            // pre.getChildByName("sp").getComponent(sp.Skeleton).skeletonData=this.biontsSpineDataArr[biontType]
            // pre.getComponent(Biont).init(-1, biontType, false)
            // pre.getComponent(Biont).registerEventPlayerCod();
            if (biontType == biontTypeEnum.wugui || biontType == biontTypeEnum.changlong) {
                pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "walk", true)
            }
            else {
                pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "animation", true)
            }
            pre.angle = 0;
            if (Player.ins.IsImmortal) {
                pre.getChildByName("shield2").active = true;

            }

            // pre.getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT, this.beginContact)

            // find("Canvas/Camera").getComponent(Camera).orthoHeight = 1.1 * find("Canvas/Camera").getComponent(Camera).orthoHeight
          
        })
        AudioMgr.ins.playOneShot("audio/devour", 0.7)
        this.changeOtherBiontType();//改变所有生物种群

    }


    // selftChangeBiont(biontType) {
    //     if (biontType == 9) {//通关
    //         gameMgr.ins.gameEnd();
    //         return;
    //     }
    //     this.changeOtherBiontType();//改变所有生物种群
    //     this.currControlBiontType = biontType;
    //     this.node.removeAllChildren();

    //     let pre = instantiate(this.notIndependentBiontPre);
    //     pre.setParent(this.node);
    //     pre.setPosition(0, 0, 0)
    //     pre.getChildByName("sp").getComponent(sp.Skeleton).skeletonData = this.biontsSpineDataArr[biontType]
    //     pre.getChildByName("sp").getComponent(sp.Skeleton).setAnimation(0, "animation", true)
    //     pre.angle = 0;

    //     if (Player.ins.IsImmortal) {
    //         pre.getChildByName("shield2").active = true;

    //     }
    //     find("Canvas/Camera").getComponent(Camera).orthoHeight = 1.1 * find("Canvas/Camera").getComponent(Camera).orthoHeight

    //     this.hasBiontsDic.delete(999)
    //     this.hasBiontsDic.set(999, biontType)


    // }


    die() {
        if (gameMgr.ins.isGameOver == false) {
            AudioMgr.ins.playOneShot("audio/hit", 0.7)

            gameMgr.ins.isGameOver = true;
            if (this.node.children[0]) {
                console.log("siwlll")
                this.node.children[0].getChildByName("dieEffect").active = true;

                setTimeout(() => {
                    gameMgr.ins.openFailPanel();
                }, 600)
            }
        }
    }

    //改变其他生物种类，根据自己类型，随机下两个和上两个类型，在自己范围外
    changeOtherBiontType() {
        if (Player.ins.currControlBiontType > gameMgr.ins.totalBiontTypeNum-4) {
            return;
        }
        gameMgr.ins.existBiontsDic.getValueList().forEach((ele) => {
            let distance = 3000;
            if (Player.ins.currControlBiontType == 5) {
                distance = 5000
            }
            else {
                distance = 3000
            }
            if (getDistance(ele.getWorldPosition().x, ele.getWorldPosition().y, this.node.getWorldPosition().x, this.node.getWorldPosition().y) > 3000) {
                gameMgr.ins.existBiontsDic.delete(ele.getComponent(Biont).biontId);
                ele.destroy();

                let minNum;
                let maxNum;
                if (Player.ins.currControlBiontType - 2 < 0) {
                    minNum = 0
                }
                else {
                    minNum = Player.ins.currControlBiontType - 2;
                }

                if (Player.ins.currControlBiontType + 3 > gameMgr.ins.totalBiontTypeNum-2) {
                    maxNum = gameMgr.ins.totalBiontTypeNum-2
                }
                else {
                    maxNum = Player.ins.currControlBiontType + 3;
                }

                let randNumBiontType = randowNum(minNum, maxNum);

                gameMgr.ins.currExistBiontsTotalNum -= 1;

                let res = false;

                gameMgr.ins.generateBiont(randNumBiontType, 1);
            }
        })
    }

    xipre = null;
    tempPos;
    protected update(dt: number): void {
        // if (this.xipre) {
        //     let resWorldPos=this.node.getWorldPosition();
        //     this.trackTargetMove11(resWorldPos,this.xipre,200,dt);
        // }
        // if (!this.xipre) {
        //     console.log("没有")
        //     this.testxi();
        // }
    }


    testxi() {
        console.log(gameMgr.ins.existBiontsDic.length, "gameMgr.ins.existBiontsDic.length");
        this.xipre = gameMgr.ins.existBiontsDic.getValueList()[randowNum(0, gameMgr.ins.existBiontsDic.length)];
        // this.xipre.setPosition(this.node.position.x + 200, this.node.position.y, 0)
        console.log(this.xipre, "this.xipre")
    }

    /**
  * @description: 面向敌人移动
  * @return {*}
  */
    trackTargetMove11(targetPos, selfNode, speed, dt) {
        if (targetPos.x > selfNode.getWorldPosition().x) {
            selfNode.setPosition(selfNode.getPosition().x + 20, selfNode.getPosition().y);
        }
        else {
            selfNode.setPosition(selfNode.getPosition().x - 20, selfNode.getPosition().y);
        }

        if (targetPos.y > selfNode.getWorldPosition().y) {
            selfNode.setPosition(selfNode.getPosition().x, selfNode.getPosition().y + 20);
        }
        else {
            selfNode.setPosition(selfNode.getPosition().x, selfNode.getPosition().y - 20);
        }


        // //如果自己已经到达敌人附近，自己销毁
        // if (isNearlyEqual(selfNode.position.y, targetPos.y)) {
        //     this.xipre = null;
        //     if (selfNode.isValid()) {
        //     selfNode.removeFromParent()

        //     }
        // }
    }


}


